package com.runfast.waimai.web.controller.company;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.utils.TimeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * ${DESCRIPTION} 城市经理管理
 *
 * @author chenzheng
 * @create 2018-05-21 17:33
 **/
@RestController("cityManagerController")
@RequestMapping("/server/cityManager")
public class CityManagerController {
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BaseUserRoleService baseUserRoleService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private RunfastGoodsSellRecordService runfastGoodsSellRecordService;
    @Autowired
    private WaiMaiRunfastAgentaccountsService waiMaiRunfastAgentaccountsService;
    /**
     * 城市经理列表带分页的
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable, Map<String, Object> params){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        BaseUser admin = SessionContext.getAdmin();
        List<BaseUser> list=null;
        Integer total=null;
        if(admin!=null && admin.getType()==1){
            BaseUserExample example=new BaseUserExample();
            //flage=6城市经理  flage=7区域代理
            example.createCriteria().andFlagEqualTo(6);
            list=baseUserService.selectByExampleWithPageable(example,pageable);
            if(list.size()>0){
                for(BaseUser user:list){
                    if(StringUtils.isNotBlank( user.getAgentids())){
                        List<String> result = Arrays.asList(user.getAgentids().split(","));
                        List<WaiMaiRunfastAgentbusiness> waiMaiRunfastAgentbusinessList=new ArrayList<WaiMaiRunfastAgentbusiness>();
                        for(String s:result){
                            int a = Integer.parseInt(s);
                            WaiMaiRunfastAgentbusiness agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(a);
                            if(agentbusiness1!=null){
                                WaiMaiRunfastAgentaccountsExample example1=new WaiMaiRunfastAgentaccountsExample();
                                example1.createCriteria().andAgentidEqualTo(agentbusiness1.getId()).andByrolesEqualTo("12");
                                List<WaiMaiRunfastAgentaccounts> agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(example1);
                                WaiMaiRunfastAgentaccounts agentaccounts=new WaiMaiRunfastAgentaccounts();
                                if(agentaccountsList.size()>0){
                                    agentaccounts=agentaccountsList.get(0);
                                }
                                map1.put("agentId",agentbusiness1.getId());
                                Map<Object,Object> map=runfastGoodsSellRecordService.cityData(map1);
                                agentbusiness1.setTotalAmount(new BigDecimal(map.get("totalMoney").toString()));
                                agentbusiness1.setTotalNum(Integer.valueOf(map.get("num").toString()));
                                agentbusiness1.setRname("代理商");
                                agentbusiness1.setUsername(agentaccounts.getAccounts());
                                waiMaiRunfastAgentbusinessList.add(agentbusiness1);
                            }
                        }
                        user.setWaiMaiRunfastAgentbusinessList(waiMaiRunfastAgentbusinessList);
                    }
                }
            }
            total=baseUserService.countByExample(example);
        }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }


    /**单个城市经理数据查询*/
    @GetMapping("/selectCityManager")
    public Result selectCityManager(Integer id,String date) throws ParseException {
        BaseUser baseUser=new BaseUser();
        if(id!=null && StringUtils.isNotBlank(date)){
            Map<Object,Object> map1=new HashMap<Object, Object>();
            baseUser=baseUserService.selectByPrimaryKey(id);
            if(baseUser!=null){
                if(StringUtils.isNotBlank( baseUser.getAgentids())){
                    List<WaiMaiRunfastAgentbusiness> waiMaiRunfastAgentbusinessList=new ArrayList<WaiMaiRunfastAgentbusiness>();
                    List<String> result = Arrays.asList(baseUser.getAgentids().split(","));
                    for(String s:result){
                        int a = Integer.parseInt(s);
                        WaiMaiRunfastAgentbusiness agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(a);
                        if(agentbusiness1!=null){
                            WaiMaiRunfastAgentaccountsExample example1=new WaiMaiRunfastAgentaccountsExample();
                            example1.createCriteria().andAgentidEqualTo(agentbusiness1.getId()).andByrolesEqualTo("12");
                            List<WaiMaiRunfastAgentaccounts> agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(example1);
                            WaiMaiRunfastAgentaccounts agentaccounts=new WaiMaiRunfastAgentaccounts();
                            if(agentaccountsList.size()>0){
                                agentaccounts=agentaccountsList.get(0);
                            }
                            /**查询时间*/
                            List<String> result1 = Arrays.asList(date.split(","));
                            map1.put("startTime",TimeUtil.getDate(result1.get(0)));
                            map1.put("endTime",TimeUtil.getDate(result1.get(1)));
                            map1.put("agentId",agentbusiness1.getId());
                            Map<Object,Object> map=runfastGoodsSellRecordService.cityData(map1);
                            agentbusiness1.setTotalAmount(new BigDecimal(map.get("totalMoney").toString()));
                             //agentbusiness1.setTotalAgentIncome(new BigDecimal(map.get("totalAgentBusget").toString()));
                            agentbusiness1.setTotalNum(Integer.valueOf(map.get("num").toString()));
                            agentbusiness1.setRname("代理商");
                            agentbusiness1.setUsername(agentaccounts.getAccounts());
                            waiMaiRunfastAgentbusinessList.add(agentbusiness1);
                        }
                    }
                    baseUser.setWaiMaiRunfastAgentbusinessList(waiMaiRunfastAgentbusinessList);
                }
            }else{return Result.fail(null,"找不到对应的区域代理！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null,baseUser);
    }
    /**
     * 保存城市经理
     */
    @PostMapping("/save")
    public Result save(@RequestBody RunfastAgentMgr agentMgr){
        if(agentMgr!=null && StringUtils.isNotBlank(agentMgr.getMobile())&& StringUtils.isNotBlank(agentMgr.getRealname()) &&StringUtils.isNotBlank(agentMgr.getUsername())
                && StringUtils.isNotBlank(agentMgr.getAgentids())){
            BaseUser admin = SessionContext.getAdmin();
            if(admin!=null && admin.getType()==1){
                //后台人员登录--只能总部人员才有权限
                BaseUserExample example=new BaseUserExample();
                example.createCriteria().andUsernameEqualTo(agentMgr.getUsername());
                Integer in=baseUserService.countByExample(example);
                if(in>0){
                    return Result.fail(null,"该登录账号已经注册过了！");
                }
                BaseUser u=new BaseUser();
                u.setRealname(agentMgr.getRealname());
                u.setCreatetime(new Date());
                u.setUsername(agentMgr.getUsername());
                u.setPassword(agentMgr.getPassword());
                u.setAgentids(agentMgr.getAgentids());
                u.setMobile(agentMgr.getMobile());
                u.setState(0);
                u.setPassword(DigestUtils.md5Hex("123456"));
                u.setFlag(6);
                baseUserService.insertSelective(u);
                BaseUserRole userRole=new BaseUserRole();
                userRole.setUserid(u.getId());
                userRole.setRid(19);
                baseUserRoleService.insertSelective(userRole);
            }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 修改城市经理
     */
    @PostMapping("/update")
    public Result update(@Valid @RequestBody RunfastAgentMgr agentMgr){
        if(agentMgr.getId()!=null &&agentMgr!=null && StringUtils.isNotBlank(agentMgr.getMobile())&& StringUtils.isNotBlank(agentMgr.getRealname())
                &&StringUtils.isNotBlank(agentMgr.getUsername()) && StringUtils.isNotBlank(agentMgr.getAgentids())){
            BaseUser admin = SessionContext.getAdmin();
            if(admin!=null && admin.getType()==1){
                BaseUser u=baseUserService.selectByPrimaryKey(agentMgr.getId());
                BaseUserExample example=new BaseUserExample();
                example.createCriteria().andUsernameEqualTo(agentMgr.getUsername()).andIdNotEqualTo(u.getId());
                Integer in=baseUserService.countByExample(example);
                if(in>0){
                    return Result.fail(null,"该登录账号已经注册过了！");
                }
                u.setRealname(agentMgr.getRealname());
                u.setUsername(agentMgr.getUsername());
                u.setAgentids(agentMgr.getAgentids());
                u.setMobile(agentMgr.getMobile());
                u.setFlag(6);
                baseUserService.updateByPrimaryKeySelective(u);
                //后台人员登录--只能总部人员才有权限
            }else{return Result.fail(null,"此功能只有总公司人员才有权限！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 删除城市经理
     */
    @GetMapping("/delete")
    public Result delete(Integer id){
        if(id!=null){
            BaseUser user=baseUserService.selectByPrimaryKey(id);

        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**修改密码*/
    @GetMapping("/setPassword")
    public Result setPassword(Integer id,String password){
        if(id!=null && StringUtils.isNotBlank(password)){
            BaseUser baseUser=baseUserService.selectByPrimaryKey(id);
            if(baseUser!=null){
                baseUser.setPassword(password);
                baseUserService.updateByPrimaryKeySelective(baseUser);
            }else{return Result.fail(null,"找不到对应的城市经理！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }

    /**
     * 城市经理列表
     */
    @GetMapping("/cityManagerlist")
    public Result cityManagerlist(@PageableDefault Pageable pageable, String mobile,String username){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        map1.put("rid",19); //城市经理的rid==19
        map1.put("pageable",pageable);
        if(StringUtils.isNotBlank(mobile)){
            map1.put("mobile",mobile);
        }
        if(StringUtils.isNotBlank(username)){
            map1.put("username",username);
        }
        List<BaseUser> userList=baseUserService.selectUserByExampleWithPageable(map1);
        Integer total=baseUserService.countUserByExample(map1);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",userList);
        map.put("total",total);
        return Result.ok(null,map);
    }



    /**
     * 城市经理列表
     */
   /* @GetMapping("/select")
    //@RequiresPermissions("server:goodsSellType:select")
    public Result select(){
        List<RunfastGoodsSellType> list = runfastGoodsSellTypeService.selectByExample(null);
        return Result.ok(null,list);
    }*/

}
